/**
 * Created by Tuffy on 16/1/18.
 */
'use strict';

angular.module('starter.controllers')

.controller('BillsCtrl', ['$rootScope', '$scope', '$state', '$cordovaToast', '$ionicLoading', '$timeout', 'BillService', '$ionicPopup',
    function($rootScope, $scope, $state, $cordovaToast, $ionicLoading, $timeout, BillService, $ionicPopup) {

    $scope.accountBalance = 0.00;//账户余额
    $scope.rate = '0%';//汇率
    $scope.bill = {
        page: {
            pageNum:1,
            pageSize:10,
            total:[]
        },
        loaded:true,
        data:[],

        loadData:function(okFunc){

            var _this = this,
                params = {
                    pageNum:_this.page.pageNum,
                    pageSize:_this.page.pageSize
                };

            _this.loaded = false;

            BillService.findBillList(params)
                .success(function(res){
                    if(res.success){
                        if(typeof(okFunc)=='function'){
                            okFunc();
                        }
                        var _data = res.attribute.rows;
                        if(!_data || _data.length<=0){
                            _this.moreDataCanBeLoaded = false;
                            $cordovaToast.showShortBottom('已加载到尾页');
                            return;
                        }
                        _this.data = _this.data.concat(_data);
                        _this.page.total = res.attribute.total;
                    }else{
                        _this.page.total = 0;
                        console.log('加载失败');
                    }
                }).error(function(error){
                _this.page.total = 0;
                console.log(error);
            }).finally(function(){

                _this.loaded = true;
                if(_this.page.total<=0){
                    _this.moreDataCanBeLoaded = false;
                }
                $scope.$broadcast('scroll.refreshComplete');
                $scope.$broadcast('scroll.infiniteScrollComplete');
            });
        },
        moreDataCanBeLoaded:true,

        loadMore:function(){
            this.page.pageNum++;
            this.loadData();
        },
        refresh:function(){
            this.page.pageNum = 1;
            this.moreDataCanBeLoaded = true;
            this.data = [];
            this.loadData();
            //var _this = this;
            //_this.page.pageNum = 1;
            //_this.data = [];
            //_this.loadData();
        },
        accountBalance:function(){
            //查询账户余额
            BillService.findAccountBalance()
                .success(function(res){
                    if(res.success){
                        $scope.accountBalance = res.attribute.billCost;//账户余额
                        $scope.rate = res.attribute.rate;//汇率
                    }else{
                        console.log('加载失败');
                    }
                }).error(function(error){
                    console.log(error);
            });
        }
    } ;
    // 详细信息
    $scope.gotoDetail = function(bill) {
        $state.go('app.bill-detail', {bill: bill});
    };

    $scope.bill.loadData();
    $scope.bill.accountBalance();

    // 提现页面弹出
    var cashModal = null;

    $scope.openCashModal = function() {

        // umeng count
        $rootScope.umengEventObj.onEventById('bill_cash');

        cashModal = $ionicPopup.show({
            templateUrl: 'templates/modal/side-bill-cash.html',
            cssClass: 'crm-login-popup',
            title: '提现',
            scope: $scope
        });
    };

    $scope.closeCashModal = function() {
        cashModal.close();
    };

    $scope.cashForm = {
        drawCash: ''
    };
    $scope.confirmCash = function() {

        if ($scope.cashForm.drawCash == '') {
            $cordovaToast.showShortBottom('提现金额不能为空,请输入正确金额');
            return;
        }

        if ($scope.cashForm.drawCash == 0) {
            $cordovaToast.showShortBottom('提现金额不能为0元,请输入正确金额');
            return;
        }

        if ($scope.cashForm.drawCash < 0) {
            $cordovaToast.showShortBottom('提现金额必须大于0,请输入正确金额');
            return;
        }

        if ($scope.cashForm.drawCash.indexOf(".") > 0 && $scope.cashForm.drawCash.split(".")[1].length > 2) {
            $cordovaToast.showShortBottom('提现金额最多小数点后两位,请检查');
            return;
        }

        // 把提现金额和实际金额取到,然后对比,是否可取现
        if ($scope.cashForm.drawCash <= $scope.accountBalance) {
            cashModal.close();

            $ionicLoading.show({
                template: '申请发送中...'
            });

            var params = {};

            params['drawCash'] = $scope.cashForm.drawCash;
            params['userId'] = $rootScope.localStorageObj.userId;

            BillService.drawAccountCash(params)
                .success(function(res){
                    if (res.success) {
                        $cordovaToast.showShortBottom('您的提现申请已发送成功');
                        $scope.bill.page.pageNum = 1;
                        $scope.bill.moreDataCanBeLoaded = true;
                        $scope.bill.data = [];
                        $scope.bill.loadData();
                        $scope.bill.accountBalance();
                    } else {
                        $cordovaToast.showShortBottom(res.errorMsg);
                    }

                })
                .error(function(error){
                    console.log(error);
            });

            $ionicLoading.hide();
        } else {
            $cordovaToast.showShortBottom('提现金额不能大于拥有金额');
        }

    };

}])
.service('BillService',['CrmHttp','$rootScope',function(CrmHttp,$rootScope){
    var url = '/crm/crm-bill/';
    return {
        /**
         * 全部结算数据
         * @param params
         * @returns {*}
         */
        findBillList: function (params) {
            var act = 'findBillList';
            params['userId'] = $rootScope.localStorageObj.userId;
            return CrmHttp.post(url + act, params);
        },
        /**
         * 全部单条结算数据
         * @param params
         * @returns {*}
         */
        findBillById: function (params) {
            var act = 'findBillById';
            return CrmHttp.post(url + act, params);
        },
        /**
         * 查询账户余额
         * @param params
         * @returns {*}
         */
        findAccountBalance: function () {
            var act = 'findAccountBalance',
                params = {};
            params['userId'] = $rootScope.localStorageObj.userId;
            return CrmHttp.post(url + act, params);
        },
        /**
         * 提现
         * @param params
         */
        drawAccountCash:function (params) {
            var act = 'drawAccountCash';

            return CrmHttp.post(url + act, params);
        }
    };
}]);